<template>
  <div class="add-product-box">
    <el-form
      :disabled="disabled"
      ref="form"
      class="form-box"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      label-width="120px"
    >
      <el-form-item label="标题" prop="title" :rules="rules.tips">
        <el-input
          v-model="ruleForm.title"
          placeholder="请输入"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="关键词" prop="keywords" :rules="rules.tips">
        <el-input
          v-model="ruleForm.keywords"
          type="textarea"
          placeholder="请输入"
          maxlength="250"
          rows="1"
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="ruleForm.description"
          type="textarea"
          placeholder="请输入"
          maxlength="250"
          rows="2"
        />
      </el-form-item>
      <el-divider />
      <el-row>
        <el-col :span="16">
          <el-form-item
            label="产品名称"
            prop="product_name"
            :rules="rules.tips"
          >
            <el-input
              v-model="ruleForm.product_name"
              placeholder="请输入"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="推荐到首页" prop="top">
            <el-switch
              v-model="ruleForm.top"
              active-color="#13ce66"
              inactive-color="#EEE"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider />
      <h2>类目</h2>
      <el-form-item label="一级类目" prop="category1">
        <el-input
          v-model="ruleForm.category1"
          placeholder="请输入"
          maxlength="250"
        />
      </el-form-item>
      <el-form-item label="二级类目" prop="category2">
        <el-input
          v-model="ruleForm.category2"
          placeholder="请输入"
          maxlength="250"
        />
      </el-form-item>
      <el-form-item label="三级类目" prop="category3">
        <el-input
          v-model="ruleForm.category3"
          placeholder="请输入"
          maxlength="250"
        />
      </el-form-item>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Banner</span>
        <div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="addBanner(ruleForm.banner)"
            >添 加</el-button
          >
        </div>
      </h2>
      <div v-for="(item, bannerIndex) in ruleForm.banner" :key="bannerIndex">
        <div class="banner-box flex-space-between align-items-center">
          <ProductForm
            :ref="`bannerForm${bannerIndex}`"
            v-model="ruleForm.banner[bannerIndex]"
            class="flex1"
          />
          <div>
            <el-button
              v-if="bannerIndex > 0"
              type="danger"
              @click="delData(ruleForm.banner, bannerIndex)"
              >删除</el-button
            >
          </div>
        </div>
      </div>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Banner-属性</span>
      </h2>
      <div class="flex-space-between align-items-center">
        <el-form-item label="列表样式类型" prop="listType">
          <Select
            v-model="ruleForm.listType"
            :list="lst_listType"
            :show-all="false"
          />
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttr(ruleForm.attributes)"
          >添 加</el-button
        >
      </div>
      <div
        v-for="(item, attrIndex) in ruleForm.attributes"
        :key="`attributes${attrIndex}`"
        class="flex-space-between align-items-center"
      >
        <Labelvalue
          :ref="`attributes${attrIndex}`"
          v-model="ruleForm.attributes[attrIndex]"
          class="flex1"
        />
        <el-button
          v-show="attrIndex > 0"
          type="danger"
          @click="delData(ruleForm.attributes, attrIndex)"
        >
          删 除
        </el-button>
      </div>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Product Detail-详情</span>
      </h2>
      <el-form-item label="描述" prop="detail.des" :rules="rules.tips">
        <el-input
          v-model="ruleForm.detail.des"
          type="textarea"
          placeholder="请输入"
          rows="10"
        />
      </el-form-item>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Paragraph-段落</span>
        <el-button type="primary" icon="el-icon-plus" @click="addParagraph">
          添 加
        </el-button>
      </h2>
      <div
        v-for="(item, detailIndex) in ruleForm.detail.paragraph"
        :key="`paragraph${detailIndex}`"
        class="flex-space-between align-items-center banner-box"
      >
        <div class="flex1">
          <el-form-item label="列表样式类型" :rules="rules.tips">
            <Select
              v-model="ruleForm.detail.paragraph[detailIndex].listType"
              :list="lst_listType"
              :show-all="false"
            />
          </el-form-item>
          <ParagraphForm
            :ref="`paragraph${detailIndex}`"
            v-model="ruleForm.detail.paragraph[detailIndex].banner"
            class="flex1"
          />
          <div
            v-for="(item, attrIndex) in ruleForm.detail.paragraph[detailIndex].attributes"
            :key="`paragrapha${detailIndex}${attrIndex}`"
            class="flex-space-between align-items-center"
          >
            <Labelvalue
              :ref="`detailattrs${detailIndex}${attrIndex}`"
              v-model="
                ruleForm.detail.paragraph[detailIndex].attributes[attrIndex]
              "
              class="flex1"
            />
            <div>
              <el-button
                v-if="attrIndex === 0"
                type="primary"
                icon="el-icon-plus"
                @click="
                  addAttr(ruleForm.detail.paragraph[detailIndex].attributes)
                "
              >
                添 加
              </el-button>
              <el-button
                v-if="attrIndex > 0"
                type="danger"
                @click="
                  delData(
                    ruleForm.detail.paragraph[detailIndex].attributes,
                    attrIndex
                  )
                "
              >
                删 除
              </el-button>
            </div>
          </div>
        </div>
        <el-button
          v-if="detailIndex > 0"
          type="danger"
          @click="delData(ruleForm.detail.paragraph, detailIndex)"
        >
          删 除
        </el-button>
      </div>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Technical Information-技术（大图）</span>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addBanner(ruleForm.technical.process)"
        >
          添 加
        </el-button>
      </h2>
      <template
        v-if="ruleForm.technical.process && ruleForm.technical.process.length"
      >
        <div
          v-for="(item, processIndex) in ruleForm.technical.process"
          :key="`process${processIndex}`"
        >
          <div class="banner-box flex-space-between align-items-center">
            <ProductForm
              :ref="`processForm${processIndex}`"
              v-model="ruleForm.technical.process[processIndex]"
              class="flex1"
            />
            <div>
              <el-button
                v-if="processIndex > 0"
                type="danger"
                @click="delData(ruleForm.technical.process, processIndex)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </template>
      <el-divider />
      <h2 class="flex-space-between align-items-center">
        <span>Technical Information-信息</span>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addInformation(ruleForm.technical.information)"
        >
          添 加
        </el-button>
      </h2>
      <template
        v-if="
          ruleForm.technical.information &&
          ruleForm.technical.information.length
        "
      >
        <div
          v-for="(item, informationIndex) in ruleForm.technical.information"
          :key="`information${informationIndex}`"
        >
          <div class="banner-box flex-space-between align-items-center">
            <InformationForm
              :ref="`information${informationIndex}`"
              v-model="
                ruleForm.technical.information[informationIndex].content[0]
              "
              class="flex1"
            />
            <div>
              <el-button
                v-if="informationIndex > 0"
                type="danger"
                @click="
                  delData(ruleForm.technical.information, informationIndex)
                "
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
      </template>
      <el-divider />
      <el-form-item label="质量" prop="quality.category" :rules="rules.select">
        Inspection<br />
        <Select
          disabled
          v-model="type"
          :list="list_category"
          :show-all="false"
        />
      </el-form-item>
      <el-divider />
      <el-form-item
        label="包装"
        prop="packaging.category"
        :rules="rules.select"
      >
        Packaging<br />
        <Select
          disabled
          v-model="type"
          :list="list_category"
          :show-all="false"
        />
      </el-form-item>
    </el-form>

    <div class="submitBtn">
      <el-button v-if="!disabled" type="primary" @click="onSubmit"
        >保 存</el-button
      >
    </div>
  </div>
</template>

<script>
import { postProduct, getProduct, editProduct, trans } from "@/api/index";
import ProductForm from "@/views/product/product-form.vue";
import InformationForm from "@/views/product/information-form.vue";
import ParagraphForm from "@/views/product/paragraph-form.vue";
import Labelvalue from "@/views/product/labelvalue.vue";
import Select from "@/components/Select/index.vue";
import FormMixin from "@/views/product/form-mixin.js";
export default {
  name: "AddDownload",
  mixins: [FormMixin],
  components: {
    ProductForm,
    Select,
    Labelvalue,
    ParagraphForm,
    InformationForm,
  },
  data() {
    return {
      type: 1,
      list_category: [
        { label: "类型1", value: 1 },
        { label: "类型2", value: 2 },
      ],
      ruleForm: {
        // 是否推荐到首页
        top: false,
        /** 标题 */
        title: null,
        keywords: null,
        /** 描述 */
        description: null,
        product_name: null,
        category1: null,
        category3: null,
        category2: null,
        banner: [
          {
            type: "img",
            img: null,
            title: null,
            banner: null,
            des: null,
            link: null,
          },
        ],
        listType: ".",
        attributes: [
          {
            name: "直径",
            value: "0.40-36mm",
            isImportant: false,
          },
        ],
        detail: {
          des: "",
          paragraph: [
            {
              title: "",
              listType: ".",
              attributes: [
                {
                  name: "",
                  value: "",
                  isImportant: false,
                },
              ],
              banner: {
                img: "",
                link: "",
                type: "img",
                title: "",
              },
            },
          ],
        },
        technical: {
          process: [
            {
              type: "img",
              des: "",
              img: "",
              banner: "",
              link: "",
              title: "",
            },
          ],
          information: [
            {
              title: "",
              content: [
                {
                  title: "",
                  tips: "",
                  table: "",
                  des: "",
                },
              ],
            },
          ],
        },
        quality: {
          category: 1,
        },
        packaging: {
          category: 1,
        },
      },
      lst_listType: [
        { label: "中心点", value: "." },
        { label: "-", value: "-" },
        { label: "序号", value: "）" },
        { label: "无", value: "" },
      ],
      rules: {
        description: [{ required: true, message: "请输入", trigger: "blur" }],
        tips: [{ required: true, message: "请输入", trigger: "blur" }],
        select: [{ required: true, message: "请选择", trigger: "change" }],
      },
      id: null,
    };
  },
  async created() {
    this.type = Number(this.$route.query.type) || 1;
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      let res = await getProduct({ id: this.$route.query.id });
      this.ruleForm = JSON.parse(res.data.content);
      if (this.ruleForm.detail.paragraph) {
        this.ruleForm.detail.paragraph.forEach((item, index) => {
          if (item.banner)
            this.$set(item.banner, "type", item.banner.type || "img");
        });
      }
     /*  console.log(
        "this.ruleForm.detail.paragraph",
        this.ruleForm.detail.paragraph
      ); */
      // 如果name 本身是空的，则直接删掉
      if (!this.ruleForm.detail.paragraph[0].attributes.name) {
        this.ruleForm.detail.paragraph[0].attributes.shift()
      }
      // 如果name 本身是空的，则直接删掉
      if (!this.ruleForm.detail.paragraph[0].attributes[this.ruleForm.detail.paragraph[0].attributes.length - 1].name) {
        !this.ruleForm.detail.paragraph[0].attributes.pop()
      }
      this.$set(this.ruleForm, "top", Boolean(this.ruleForm.top));
      this.ruleForm.category.forEach((item, index) => {
        this.ruleForm[`category${index + 1}`] = item;
      });
    }
  },
  methods: {
    async onSubmit() {
      try {
       
        // 验证页面基础信息
        await this.$refs.form.validate();
        // 验证banner
        const bannersValidates = this.ruleForm.banner.map((item, index) =>
          this.$refs[`bannerForm${index}`][0].validate()
        );
        await Promise.all(bannersValidates);
        // 验证属性
        const attributesValidates = this.ruleForm.attributes.map(
          (item, index) => this.$refs[`attributes${index}`][0].validate()
        );
        await Promise.all(attributesValidates);
        // 验证 详情内容
        const detailParagraphValidates = this.ruleForm.detail.paragraph.map(
          (item, index) => this.$refs[`paragraph${index}`][0].validate()
        );
        await Promise.all(detailParagraphValidates);
        // 验证 详情label value
        const detailAttrsValidates = [];
        this.ruleForm.detail.paragraph.forEach((item, index) => {
          item.attributes.forEach((attr, attrIndex) => {
            detailAttrsValidates.push(
              this.$refs[`detailattrs${index}${attrIndex}`][0].validate()
            );
          });
        });
        await Promise.all(detailAttrsValidates);
        // 验证 技术
        const processValidates = this.ruleForm.technical.process.map(
          (item, index) => this.$refs[`processForm${index}`][0].validate()
        );
        await Promise.all(processValidates);
        // 验证 信息
        const informationValidates = this.ruleForm.technical.information.map(
          (item, index) => this.$refs[`information${index}`][0].validate()
        );
        await Promise.all(informationValidates);
        let formData = new FormData();
        !this.id && formData.append("type", this.type);
        this.id && formData.append("id", this.id);
        /** 类目格式化 */
        let content = {
          ...this.ruleForm,
          category: [
            this.ruleForm.category1,
            this.ruleForm.category2,
            this.ruleForm.category3,
          ].filter((item) => item),
        };
        formData.append("content", JSON.stringify(content));
        let fetchApi = this.id ? editProduct : postProduct;
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        await fetchApi(formData);
        await trans(this.id)
        this.$message({
          type: "success",
          message: "成功",
        });
        loading.close()
        !this.id && this.$router.push("/product");
      } catch (error) {
        console.log("error", error);
      }
    },
    addInformation(data) {
      data.push({
        title: "",
        content: [
          {
            title: "",
            tips: "",
            table: "",
            des: "",
          },
        ],
      });
    },
    addParagraph() {
      this.ruleForm.detail.paragraph.push({
        title: "",
        listType: ".",
        attributes: [
          {
            name: "",
            value: "",
            isImportant: false,
          },
        ],
        banner: {
          img: "",
          link: "",
          type: "img",
          title: "",
        },
      });
    },
    addAttr(data) {
      data.push({
        name: "",
        value: "",
        isImportant: false,
      });
    },
    addBanner(data) {
      data.push({
        type: "img",
        img: null,
        title: null,
        banner: null,
        des: null,
        link: null,
      });
    },
    async delData(data, index, tips) {
      await this.$confirm(`此操作将删除${tips || "数据"}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      data.splice(index, 1);
    },
  },
};
</script>
<style lang="scss">
.add-product-box {
  height: calc(100vh - 90px);
  padding: 10px;
  display: flex;
  flex-direction: column;
  .form-box {
    flex: 1;
    overflow-y: auto;
  }
  .banner-box {
    border: 1px solid #ebeef5;
    margin-bottom: 10px;
    padding: 5px;
  }
}
.submitBtn{
  text-align: center;
  border-top: 1px solid #eee;
  width: 96%;
  margin: 10px auto;
  padding-top: 20px;
}
.submitBtn button{
  width: 200px;
}
</style>
